<template>
  <div class="team-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">{{ $t('team.management') }}</h1>
        <p class="page-description">{{ $t('team.managementDesc') }}</p>
      </div>
      <div class="header-right">
        <el-button
          :icon="User"
          @click="showJoinDialog = true"
        >
          {{ $t('team.joinTeam') }}
        </el-button>
        <el-button
          type="primary"
          :icon="Plus"
          @click="showCreateDialog = true"
          :disabled="!canCreateTeam"
        >
          {{ $t('team.createTeam') }}
        </el-button>
        <el-button
          :icon="Refresh"
          @click="refreshTeams"
          :loading="teamStore.loading"
        >
          {{ $t('common.refresh') }}
        </el-button>
      </div>
    </div>

    <!-- 团队筛选 -->
    <div class="team-filters">
      <el-radio-group v-model="activeTab" @change="handleTabChange">
        <el-radio-button value="all">{{ $t('team.allTeams') }}</el-radio-button>
        <el-radio-button value="approved">{{ $t('team.approvedTeams') }}</el-radio-button>
        <el-radio-button value="pending">{{ $t('team.pendingTeams') }}</el-radio-button>
      </el-radio-group>
      
      <div class="filter-right">
        <el-input
          v-model="searchKeyword"
          :placeholder="$t('team.searchPlaceholder')"
          :prefix-icon="Search"
          clearable
          style="width: 300px"
        />
      </div>
    </div>

    <!-- 团队列表 -->
    <div class="team-list" v-loading="teamStore.loading">
      <div v-if="filteredTeams.length === 0" class="empty-state">
        <el-empty :description="$t('team.noTeams')">
          <el-button 
            type="primary" 
            @click="showCreateDialog = true"
            :disabled="!canCreateTeam"
          >
            {{ $t('team.createFirstTeam') }}
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="team-grid">
        <TeamCard
          v-for="team in filteredTeams"
          :key="team.id"
          :team="team"
          @view="handleViewTeam"
          @edit="handleEditTeam"
          @delete="handleDeleteTeam"
        />
      </div>
    </div>

    <!-- 创建团队对话框 -->
    <CreateTeamDialog
      v-model="showCreateDialog"
      @success="handleCreateSuccess"
    />

    <!-- 编辑团队对话框 -->
    <EditTeamDialog
      v-model="showEditDialog"
      :team="editingTeam"
      @success="handleEditSuccess"
    />

    <!-- 加入团队对话框 -->
    <JoinTeamDialog
      v-model="showJoinDialog"
      @success="handleJoinSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Plus, Refresh, Search, User } from '@element-plus/icons-vue'
import { useTeamStore } from '@/stores/teamStore'
import { useAuthStore } from '@/stores/auth'
import type { Team } from '@/types/team'
import TeamCard from '@/components/team/TeamCard.vue'
import CreateTeamDialog from '@/components/team/CreateTeamDialog.vue'
import EditTeamDialog from '@/components/team/EditTeamDialog.vue'
import JoinTeamDialog from '@/components/team/JoinTeamDialog.vue'

const { t } = useI18n()
const router = useRouter()
const teamStore = useTeamStore()
const authStore = useAuthStore()

// 响应式数据
const activeTab = ref('all')
const searchKeyword = ref('')
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showJoinDialog = ref(false)
const editingTeam = ref<Team | null>(null)

// 计算属性
const canCreateTeam = computed(() => {
  // 调试：打印权限检查信息
  console.log('=== 团队创建权限检查 ===')
  console.log('当前用户:', authStore.user)
  console.log('用户类型 (userType):', authStore.user?.userType)
  console.log('authStore.canCreateTeam:', authStore.canCreateTeam)
  console.log('========================')

  // 直接使用auth store的计算属性
  return authStore.canCreateTeam
})

const filteredTeams = computed(() => {
  let teams = teamStore.teams

  // 根据标签筛选
  switch (activeTab.value) {
    case 'approved':
      teams = teamStore.approvedTeams
      break
    case 'pending':
      teams = teamStore.pendingTeams
      break
    default:
      teams = teamStore.teams
  }

  // 根据搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    teams = teams.filter(team => 
      team.name.toLowerCase().includes(keyword) ||
      team.description?.toLowerCase().includes(keyword)
    )
  }

  return teams
})

// 方法
const refreshTeams = async () => {
  try {
    await teamStore.fetchMyTeams()
  } catch (error) {
    console.error('刷新团队列表失败:', error)
  }
}

const handleTabChange = () => {
  // 标签切换时的处理逻辑
}

const handleViewTeam = (team: Team) => {
  router.push(`/dashboard/team/${team.id}`)
}

const handleEditTeam = (team: Team) => {
  editingTeam.value = team
  showEditDialog.value = true
}

const handleDeleteTeam = async (team: Team) => {
  try {
    await teamStore.deleteTeam(team.id)
  } catch (error) {
    console.error('删除团队失败:', error)
  }
}

const handleCreateSuccess = () => {
  showCreateDialog.value = false
  ElMessage.success(t('team.createSuccess'))
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  editingTeam.value = null
  ElMessage.success(t('team.updateSuccess'))
}

const handleJoinSuccess = () => {
  showJoinDialog.value = false
  ElMessage.success(t('team.joinSuccess'))
}

// 生命周期
onMounted(() => {
  refreshTeams()
})
</script>

<style scoped lang="scss">
.team-management {
  padding: 24px;
  background: var(--el-bg-color-page);
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .header-left {
      .page-title {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .page-description {
        margin: 0;
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .team-filters {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px;
    background: var(--el-bg-color);
    border-radius: 8px;
    border: 1px solid var(--el-border-color-light);

    .filter-right {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }

  .team-list {
    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 400px;
    }

    .team-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
      gap: 20px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .team-management {
    padding: 16px;

    .page-header {
      flex-direction: column;
      gap: 16px;

      .header-right {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .team-filters {
      flex-direction: column;
      gap: 16px;

      .filter-right {
        width: 100%;
      }
    }

    .team-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>
